# -*- coding: utf-8 -*-

from qgis.core import (
    QgsGeometry,
    QgsWkbTypes,
    Qgis
)

from qgis.gui import (
    QgsRubberBand,
    QgsMapToolEmitPoint,
    QgsMapMouseEvent
)

from PyQt5.QtCore import Qt,pyqtSignal

class DrawingPolylineTool(QgsMapToolEmitPoint):
    # 绘制信号
    # str 绘制行为
    # Qgis.GeometryType 绘制类型
    # QgsGeometry 绘制图形容器
    drawGeometry = pyqtSignal(str,Qgis.GeometryType,QgsGeometry)

    def __init__(self,action, canvas):
        super().__init__(canvas)
        self.__action = action
        self.__canvas = canvas
        self.__crs = canvas.mapSettings().destinationCrs()
        
        self.__points = []
        
        self.__line_rubber_band = QgsRubberBand(self.__canvas, QgsWkbTypes.LineGeometry)
        self.__line_rubber_band.setColor(Qt.blue)
        self.__line_rubber_band.setWidth(2)

        self.__point_rubber_band = QgsRubberBand(self.__canvas, QgsWkbTypes.PointGeometry)
        self.__point_rubber_band.setColor(Qt.red)
        self.__point_rubber_band.setWidth(2)
    
    def __drawGeometry(self):
        #将点集转为Polyline
        geometry = QgsGeometry.fromPolylineXY(self.__points)
    
        # 将数据发送到信号中
        self.drawGeometry.emit(self.__action,Qgis.GeometryType.Line,geometry)

        # 从画布中移除图形容器
        # self.__canvas.scene().removeItem(self.__line_rubber_band)

        self.__clear()

    def __clear(self):
        # 清除缓存数据
        self.__points.clear()
        self.__line_rubber_band.reset(QgsWkbTypes.LineGeometry)
        self.__point_rubber_band.reset(QgsWkbTypes.PointGeometry)

    def canvasPressEvent(self, e):
        # e.isAccepted() 验证按钮是否被接收，添加了此判断之后勾绘会有卡顿
        # if e.button() == Qt.LeftButton and e.isAccepted():
        if e.button() == Qt.LeftButton:
            self.__points.append(e.mapPoint())
            self.__line_rubber_band.addPoint(e.mapPoint())
            self.__point_rubber_band.addPoint(e.mapPoint())
        elif e.button() == Qt.RightButton: # 这里可以添加处理右击事件的逻辑
            if len(self.__points) > 1:
                self.__drawGeometry()
            else:
                self.__clear()
    
    def canvasDoubleClickEvent(self, e: QgsMapMouseEvent):
        if e.button() == Qt.LeftButton and len(self.__points)>1:
            self.__drawGeometry()

    def deactivate(self):
        del self.__line_rubber_band
        del self.__point_rubber_band
        del self.__points
        super().deactivate()